package com.itheima.comment.service.impl;

import com.itheima.comment.document.Comment;
import com.itheima.comment.dto.CommentDto;
import com.itheima.comment.dto.CommentSaveDto;
import com.itheima.comment.service.CommentService;
import com.itheima.comment.vo.CommentVo;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.comment.service.impl
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private MongoTemplate mongoTemplate;
    /**
     * 发表评论
     *
     * @param dto
     */
    @Override
    public void add(CommentSaveDto dto) {
        // 匿名账号判断
        if(RequestContextUtil.getUserId() == SystemConstants.ANONYMOUS_USER_ID){
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }
        //1. 创建pojo
        Comment pojo = new Comment();
        //2. 给pojo对象属性赋值
        pojo.setHeadImage(RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_IMAGE));
        pojo.setNickName(RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_NAME));
        pojo.setUserId(RequestContextUtil.getUserId());
        pojo.setReplies(0);// 默认0
        pojo.setLikes(0); // 默认为0
        pojo.setUpdatedTime(LocalDateTime.now());
        pojo.setCreatedTime(pojo.getUpdatedTime());
        pojo.setContent(dto.getContent());
        pojo.setArticleId(dto.getArticleId());
        //3. 保存
        mongoTemplate.insert(pojo);
    }

    /**
     * 加载评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<CommentVo> load(CommentDto dto) {
        // 前端有问题，暂时为当前系统时间
        dto.setMinDate(new Date());
        //1. 构建查询条件
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        //2. 查询
        List<Comment> list = mongoTemplate.find(query, Comment.class);
        //3. 得到结果集，转成vo
        List<CommentVo> voList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            voList = list.stream().map(CommentVo::build).collect(Collectors.toList());
        }
        //4. 返回
        return voList;
    }
}
